package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.service.OrdersService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDeatilMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO addOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //处理异常（购物车为空、地址簿为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //用户下单，需要生成订单信息，
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));     //订单号
        orders.setStatus(Orders.PENDING_PAYMENT);       //订单状态：待付款
        orders.setUserId(BaseContext.getCurrentId());           //下单用户
        orders.setOrderTime(LocalDateTime.now());       //下单时间
        orders.setPayStatus(Orders.UN_PAID);        //未支付状态
        //根据地址簿id查出下单人的信息(phone、address、consignee)
        AddressBook addressBook1 = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        orders.setConsignee(addressBook1.getConsignee());
        orders.setPhone(addressBook1.getPhone());
        orders.setConsignee(addressBook1.getConsignee());
        //查询用户表，设置下单人的用户名称
        User user = userMapper.getById(BaseContext.getCurrentId());
        orders.setUserName(user.getName());
        //插入到订单表
        ordersMapper.insert(orders);
        //构造订单明细的数据
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectByUserId(BaseContext.getCurrentId());
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart1 : shoppingCarts) {
            OrderDetail od = OrderDetail.builder()
                    .name(shoppingCart1.getName())
                    .image(shoppingCart1.getImage())
                    .orderId(orders.getId())
                    .dishId(shoppingCart1.getDishId())
                    .setmealId(shoppingCart1.getSetmealId())
                    .dishFlavor(shoppingCart1.getDishFlavor())
                    .number(shoppingCart1.getNumber())
                    .amount(shoppingCart1.getAmount())
                    .build();
            orderDetails.add(od);
        }
        orderDeatilMapper.insertBatch(orderDetails);
        //清除购物车
        ShoppingCart sc = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();
        shoppingCartMapper.delete(sc);
        //构造返回对象
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = ordersMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);

        //通过websocket推送消息
        Map map = new HashMap();
        map.put("type", 1);         //1标识来单提醒，2标识客户推单
        map.put("orderId", orders.getId());
        map.put("content", "订单号是：" + orders.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public void preOrder(Long id) {
        Orders order = ordersMapper.getById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //通过websocket推送消息
        Map map = new HashMap();
        map.put("type", 2);         //1标识来单提醒，2标识客户推单
        map.put("orderId", order.getId());
        map.put("content", "订单号是：" + order.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
